<template>
    <el-main>
      <h1>电子图书文档管理</h1>
      <el-rate class="ml-1" />
      <el-row>
        <el-form :model="like">
          <el-form-item
              label="名称"
          >
            <el-input
                v-model="like.name"
                type="text"
                autocomplete="off"
            />
          </el-form-item>

        </el-form>
        <el-button type="primary" @click="submitLike(like.name)">查询</el-button>
        <el-button type="primary" @click="add()">增加</el-button>
      </el-row>


      <el-table :data="tableData"
                style="width: 100%"
                row-key="id"
                border
                lazy
                :load="load"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="ID" width="200" prop="id">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.id }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="名称" width="180" prop="name">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="顺序" width="180" prop="sort">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.sort }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="父文档" width="200">
          <template #default="scope" prop="parent">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.parent }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >Edit</el-button
            >
            <el-popconfirm
                confirm-button-text="Yes"
                cancel-button-text="No"
                title="确定要删除吗?"
                @confirm="confirmEvent(scope.row.id)"
            >
              <template #reference>
                <el-button
                    size="small"
                    type="danger"
                >Delete</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage3"
          v-model:page-size="pageSize3"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper,total,->,consists of sizes"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
      <el-dialog v-model="dialogFormVisible" title="电子书文档表单">
        <el-form :model="form" :rules="rules" ref="ruleFormRef">
          <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="顺序" :label-width="formLabelWidth">
            <el-input v-model.number="form.sort" autocomplete="off" />
          </el-form-item>
          <el-form-item label="父文档" :label-width="formLabelWidth">
            <el-cascader
                v-model="form.parent"
                :options="options"
                :props="props"
                clearable
                placeholder="请选择父文档"
            />
          </el-form-item>
          <el-form-item label="内容" :label-width="formLabelWidth">
            <div style="border: 1px solid #ccc">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  mode="default"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="update(ruleFormRef)">
          更新
        </el-button>
         </span>
        </template>
      </el-dialog>
    </el-main>

</template>
<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount,shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Timer } from '@element-plus/icons-vue'
import {h, onMounted, ref,reactive} from "vue";
import axios from "axios";
import {ElNotification, FormInstance, FormRules} from "element-plus";
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";



// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref()

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor:any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const ruleFormRef = ref<FormInstance>()


const tableData: doc[] = ref([])
const currentPage3 = ref(1)
const pageSize3 = ref(10)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const total=ref(10)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const options=ref()
const route=useRoute()
const props = {
  expandTrigger: 'hover' as const,
  value:'id',
  label: 'name',
  children: 'children',
  checkStrictly: true,
}
const load = (
    row: doc,
    treeNode: unknown,
    resolve: (date: doc[]) => void
) => {
  let arr:any=[]
  axios({
    method: 'get',
    url: '/doc/listChildren',
    // 传递参数
    params: {
      "id":row.id
    },
    // 设置请求头信息
    headers: {

    }
  }).then((response) => {
    if (response.data.data.length!==0){
      open1("teal",response.data.message)
      arr=response.data.data
      for (let i = 0; i < arr.length; i++) {
          arr[i]["hasChildren"]=true
      }
    }else {
      open1("red",response.data.message)
    }
  })
  setTimeout(() => {
    resolve(arr)
  }, 1000)
}

const like = reactive({
  name: '',
})
const form = reactive({
  id:0,
  parent:0,
  name: '',
  sort:0,
})
interface doc {
  id:number
  parent: number
  name: string
  sort:number
  ebookId:number,
  viewCount:number,
  voteCount:number,
  hasChildren?: boolean
  children?: doc[]
}
const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
})
const handleQuery=(params:any)=>{
  axios({
    method: 'get',
    url: '/doc/list',
    // 传递参数
    params: {
      "name": params.name,
      "ebookId":route.query.ebookId,
      "pageNum":params.pageNum,
      "pageSize":params.pageSize,
    },
    // 设置请求头信息
    headers: {

    }
  }).then((response) => {
    tableData.value=response.data.data.data
    for (let i = 0; i < tableData.value.length; i++) {
      let a= tableData.value[i]
      a["hasChildren"]=true
    }
    total.value=response.data.data.total
  })
}

const handleQueryContent=()=>{
  axios({
    method: 'get',
    url: '/doc/oneContent/'+form.id,
  }).then((response) => {
    valueHtml.value=response.data.data
  })
}


const confirmEvent=(id:number)=>{
  axios({
    method: 'delete',
    url: '/doc/delete/'+id
  }).then((response) => {
    if (response.data.data!==0){
      handleQuery({
        "name":"",
        "pageNum":currentPage3.value,
        "pageSize":pageSize3.value
      })
      open1("teal",response.data.message)
    }else {
      open1("red",response.data.message)
    }
  })
}

const setDisable=(treeSelectData:any,id:number)=>{
  for (let i = 0; i < treeSelectData.length; i++) {
    let node=treeSelectData[i]
    if (node.id===id){
      node.disabled=true
      let children=node.children
      if (Tool.isNotEmpty(children)){
        for (let j = 0; j < children.length; j++) {
          setDisable(children,children[j].id)
        }
      }
    }else {
      let children=node.children
      if (Tool.isNotEmpty(children)){
        setDisable(children,id)
      }
    }
  }
}

const all=()=>{
  axios({
    method: 'get',
    url: '/doc/all',
    // 传递参数
  }).then((response) => {
    options.value=[]
    options.value=Tool.array2Tree(response.data.data,0)
    options.value.unshift({id:0,name:"无"})
  })
}

const add=()=>{
  dialogFormVisible.value=true
  form.id=0
  form.parent=0
  form.name=''
  form.sort=0
  valueHtml.value=''
  all()
}

const submitLike=(name:string)=>{
  handleQuery({
    "name":name,
    "pageNum":currentPage3.value,
    "pageSize":pageSize3.value
  })
}

const update=async (formEl: FormInstance | undefined)=>{
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let type:string=typeof form.parent
      if (type==='object'){
        form.parent=form.parent[0]
      }
      axios({
        method: 'post',
        url: '/doc/update',
        // 传递参数
        data: {
          "id":form.id,
          "parent": form.parent,
          "name": form.name,
          "sort":form.sort,
          "ebookId":route.query.ebookId,
          "content":valueHtml.value
        },
        // 设置请求头信息
        headers: {
          "Content-Type":"application/json"
        }
      }).then((response) => {
        if (response.data.data!==0){
          tableData.value=[]
          dialogFormVisible.value = false
          handleQuery({
            "name":"",
            "pageNum":currentPage3.value,
            "pageSize":pageSize3.value
          })
          open1("teal",response.data.message)
        }else {
          open1("red",response.data.message)
        }
      })
    }
  })
}
onMounted(()=>{
  handleQuery({
    "name":"",
    "pageNum":currentPage3.value,
    "pageSize":pageSize3.value
  })
  all()
})
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  currentPage3.value=val
  handleQuery({
    "name":"",
    "pageNum":currentPage3.value,
    "pageSize":pageSize3.value
  })
}
const handleEdit = (index: number, row: doc) => {
  valueHtml.value=''
  dialogFormVisible.value=true
  form.id=row.id
  form.parent=row.parent
  form.name=row.name
  form.sort=row.sort
  handleQueryContent()
  setDisable(options.value,row.id)
  if (options.value[0].id!==0){
    options.value.unshift({id:0,name:"无"})
  }
}
const open1 = (color:string,msg:string) => {
  ElNotification({
    title: '消息',
    message: h('i', { style: 'color: '+color }, msg),
    duration:3000,
  })
}
</script>
<style scoped>

</style>

